<?php
/**
 * 数据库验证脚本
 * 用于验证本地数据库是否成功导入
 */

// 本地数据库配置
$localConfig = [
    'hostname' => 'localhost',
    'database' => 'oa5',
    'username' => 'root',
    'password' => '123456',
    'hostport' => '3306',
    'charset'  => 'utf8mb4',
];

try {
    echo "连接到本地数据库...\n";
    
    // 创建数据库连接
    $dsn = "mysql:host={$localConfig['hostname']};port={$localConfig['hostport']};dbname={$localConfig['database']};charset={$localConfig['charset']}";
    $pdo = new PDO($dsn, $localConfig['username'], $localConfig['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    
    echo "数据库连接成功！\n\n";
    
    // 获取数据库中的表数量
    $stmt = $pdo->query("SHOW TABLES");
    $tables = $stmt->fetchAll();
    $tableCount = count($tables);
    
    echo "数据库中表的数量: $tableCount\n";
    
    // 检查一些关键表是否存在
    $keyTables = [
        'oa_admin', 
        'oa_admin_rule', 
        'oa_customer', 
        'oa_contract', 
        'oa_lawcase',
        'oa_lawyer',
        'oa_user'
    ];
    
    echo "\n关键表检查:\n";
    foreach ($keyTables as $table) {
        try {
            $stmt = $pdo->query("SELECT COUNT(*) as count FROM `$table`");
            $result = $stmt->fetch();
            echo "- $table: " . $result['count'] . " 条记录\n";
        } catch (PDOException $e) {
            echo "- $table: 表不存在或访问出错\n";
        }
    }
    
    // 检查用户表中的数据
    echo "\n用户数据检查:\n";
    try {
        $stmt = $pdo->query("SELECT id, name, username FROM oa_admin LIMIT 5");
        $users = $stmt->fetchAll();
        echo "前5个用户:\n";
        foreach ($users as $user) {
            echo "- ID: {$user['id']}, 姓名: {$user['name']}, 用户名: {$user['username']}\n";
        }
    } catch (PDOException $e) {
        echo "无法查询用户数据: " . $e->getMessage() . "\n";
    }
    
    // 检查权限规则表
    echo "\n权限规则检查:\n";
    try {
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM oa_admin_rule");
        $result = $stmt->fetch();
        echo "权限规则总数: " . $result['count'] . " 条\n";
        
        // 检查模块分布
        $stmt = $pdo->query("SELECT module, COUNT(*) as count FROM oa_admin_rule GROUP BY module ORDER BY count DESC");
        $modules = $stmt->fetchAll();
        echo "各模块规则数量:\n";
        foreach ($modules as $module) {
            echo "- {$module['module']}: {$module['count']} 条规则\n";
        }
    } catch (PDOException $e) {
        echo "无法查询权限规则数据: " . $e->getMessage() . "\n";
    }
    
    echo "\n数据库验证完成！\n";
    
} catch (PDOException $e) {
    echo "数据库连接错误: " . $e->getMessage() . "\n";
} catch (Exception $e) {
    echo "验证过程中发生错误: " . $e->getMessage() . "\n";
}